package com.coffee.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.coffee.admin.api.merchant.result.MerchantResult;
import com.coffee.admin.api.merchant.service.MerchantService;
import com.coffee.core.anotation.LoginCheck;
import com.coffee.core.anotation.OperLog;
import com.coffee.core.anotation.SupplierLoginCheck;
import com.coffee.core.entity.LoginUser;
import com.coffee.core.entity.Page;
import com.coffee.core.entity.PagerInfo;
import com.coffee.core.enums.*;
import com.coffee.core.exception.BusinessException;
import com.coffee.core.result.Result;
import com.coffee.core.util.DateUtil;
import com.coffee.core.util.IpUtils;
import com.coffee.core.util.WebUtil;
import com.coffee.order.api.inquire.req.*;
import com.coffee.order.api.inquire.result.InquireOrderResult;
import com.coffee.order.api.inquire.result.InquireOrderTestingResult;
import com.coffee.order.api.inquire.result.OrderListResult;
import com.coffee.order.api.inquire.service.InquireOrderService;
import com.coffee.order.api.inquire.service.InquireOrderTestingService;
import com.coffee.order.api.sku.req.PayReq;
import com.coffee.order.api.sku.req.SkuOrderAddReq;
import com.coffee.order.api.sku.result.OrderResult;
import com.coffee.order.api.sku.result.PayOrderResult;
import com.coffee.order.api.sku.result.PayParam;
import com.coffee.order.api.sku.service.CommonPayService;
import com.coffee.order.api.sku.service.SkuOrderService;
import com.coffee.sku.api.inquire.query.InquireSkuPriceTrendQuery;
import com.coffee.sku.api.inquire.result.InquireSkuPriceTrendResult;
import com.coffee.sku.api.inquire.result.InquireSkuTestingMessageResult;
import com.coffee.sku.api.inquire.service.InquireSkuPriceTrendService;
import com.coffee.web.utils.WeixinAppletsUtil;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping
public class InquireOrderController extends BaseController {

    @Value("${parameter.webDomain}")
    private String webDomain;

    @DubboReference
    private InquireOrderService inquireOrderService;
    @DubboReference
    private CommonPayService commonPayService;
    @DubboReference
    private InquireOrderTestingService inquireOrderTestingService;
    @DubboReference
    private InquireSkuPriceTrendService inquireSkuPriceTrendService;
    @DubboReference
    private MerchantService merchantService;

    @OperLog(operModul = "商户-期货商品询价", operDesc = "期货商品询价")
    @LoginCheck
    @RequestMapping(value = "/merchant/inquire/add/order", method = {RequestMethod.POST})
    public Result<MerchantResult> orderInquiry(@RequestBody AddInquireOrderReq req, HttpServletRequest request) throws BusinessException {
        LoginUser merchant = getMerchant();
        req.setMerchantId(merchant.getUserId());
        Result<MerchantResult> result = Result.success(null);
        inquireOrderService.add(req);
        return result;
    }

    @OperLog(operModul = "商户-期货商品询价", operDesc = "期货商品询价")
    @LoginCheck
    @RequestMapping(value = "/merchant/inquire/order/permission", method = {RequestMethod.POST})
    public Result<Boolean> inquireOrderPermission(HttpServletRequest request) throws BusinessException {
        LoginUser merchant = getMerchant();
        Result<Boolean> result = Result.success(null);
        MerchantResult merchantResult = merchantService.getDetail(merchant.getUserId());
        if (merchantResult.getBuyPermission().contains(SkuTypeEnum.INQUIRE.getCode())) {
            result.setData(true);
        } else {
            result.setData(false);
        }
        return result;
    }


    @OperLog(operModul = "商户-取消订单", operDesc = "取消订单")
    @LoginCheck
    @RequestMapping(value = "/merchant/inquire/cancel/order", method = {RequestMethod.POST})
    public Result<MerchantResult> cancelOrder(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws BusinessException {
        LoginUser merchant = getMerchant();
        Integer id = jsonObject.getInteger("id");
        Result<MerchantResult> result = Result.success(null);
        inquireOrderService.cancelOrder(id, merchant.getUserId(), RoleTypeEnum.MERCHANT.getCode(), null);
        return result;
    }


    @OperLog(operModul = "商户-确认收货", operDesc = "确认收货")
    @LoginCheck
    @RequestMapping(value = "/merchant/inquire/confirm/order", method = {RequestMethod.POST})
    public Result<String> confirmOrder(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws BusinessException {
        LoginUser merchant = getMerchant();
        Integer id = jsonObject.getInteger("id");
        Result<String> result = Result.success(null);
        inquireOrderService.confirmOrder(id, merchant.getUserId(), RoleTypeEnum.MERCHANT.getCode());
        return result;
    }

    @OperLog(operModul = "商户-确认明确报价", operDesc = "期货商品询价")
    @LoginCheck
    @RequestMapping(value = "/merchant/inquire/order/buyerConfirm", method = {RequestMethod.POST})
    public Result<MerchantResult> orderBuyerConfirm(@RequestBody BuyerConfirmReq req, HttpServletRequest request) throws BusinessException {
        LoginUser merchant = getMerchant();
        req.setMerchantId(merchant.getUserId());
        Result<MerchantResult> result = Result.success(null);
        inquireOrderService.buyerConfirm(req);
        return result;
    }

    @OperLog(operModul = "商户-选择意向报价", operDesc = "期货商品询价")
    @LoginCheck
    @RequestMapping(value = "/merchant/inquire/order/buyerIntentionConfirm", method = {RequestMethod.POST})
    public Result<MerchantResult> orderBuyerIntentionConfirm(@RequestBody BuyerIntentionConfirmReq req, HttpServletRequest request) throws BusinessException {
        LoginUser merchant = getMerchant();
        req.setMerchantId(merchant.getUserId());
        Result<MerchantResult> result = Result.success(null);
        inquireOrderService.buyerIntentionConfirm(req);
        return result;
    }

    @OperLog(operModul = "商户-支付", operDesc = "支付")
    @LoginCheck
    @RequestMapping(value = "/merchant/pay/order", method = {RequestMethod.POST})
    public Result<String> orderPay(HttpServletRequest request, @RequestBody SellerConfirmReq req) {
        LoginUser merchant = getMerchant();
        Result<String> result = Result.success(null);
        try {
            req.setUserId(merchant.getUserId());
            req.setType(RoleTypeEnum.MERCHANT.getCode());
            inquireOrderService.pay(req);
        } catch (BusinessException e) {
            return Result.failed(e.getCode(), e.getMessage());
        }
        result.setData("SUCCESS");
        return result;
    }

    @OperLog(operModul = "商户-上传凭证", operDesc = "上传凭证")
    @LoginCheck
    @RequestMapping(value = "/merchant/inquire/test/order/upload", method = {RequestMethod.POST})
    public Result<String> testOrderUploadReport(@RequestBody JSONObject req, HttpServletRequest request) {
        LoginUser merchant = getMerchant();
        Result<String> result = Result.success(null);
        Integer id = req.getInteger("id");
        String cover = req.getString("cover");
        try {
            SellerConfirmReq sellerConfirmReq = new SellerConfirmReq();
            sellerConfirmReq.setUserId(merchant.getUserId());
            sellerConfirmReq.setType(RoleTypeEnum.MERCHANT.getCode());
            sellerConfirmReq.setInquireOrderId(id);
            sellerConfirmReq.setCover(cover);
            inquireOrderService.contract(sellerConfirmReq);
        } catch (BusinessException e) {
            return Result.failed(e.getCode(), e.getMessage());
        }
        result.setData("success");
        return result;
    }

    @OperLog(operModul = "商户-创建样品", operDesc = "创建样品")
    @LoginCheck
    @RequestMapping(value = "/merchant/inquire/order/sampleOrderByBuyer", method = {RequestMethod.POST})
    public Result<String> orderPay(HttpServletRequest request, @RequestBody SampleOrderReq req) {
        LoginUser merchant = getMerchant();
        Result<String> result = Result.success(null);
        try {
            req.setUserId(merchant.getUserId());
            req.setType(RoleTypeEnum.MERCHANT.getCode());
            inquireOrderService.sampleOrderByBuyer(req);
        } catch (BusinessException e) {
            return Result.failed(e.getCode(), e.getMessage());
        }
        result.setData("SUCCESS");
        return result;
    }


    @OperLog(operModul = "商户-物流付费", operDesc = "物流付费")
    @LoginCheck
    @RequestMapping(value = "/merchant/pay/logistics", method = {RequestMethod.POST})
    public Result<PayParam> orderPay(HttpServletRequest request, @RequestBody JSONObject jsonObject) {
        LoginUser merchant = getMerchant();
        Result<PayParam> result = Result.success(null);
        try {
            Integer inquireOrderDeliveryDemandId = jsonObject.getInteger("inquireOrderDeliveryDemandId");
            String returnUrl = jsonObject.getString("returnUrl");
            String openId = jsonObject.getString("openId");
            Integer appletType = jsonObject.getInteger("appletType");
            OrderResult orderResult = inquireOrderService.logisticsPayByInquire(merchant.getUserId(), inquireOrderDeliveryDemandId);
            PayReq req = new PayReq();
            req.setUserId(merchant.getUserId());
            req.setAmount(orderResult.getPayPrice());
            req.setSubject("期货物流支付");
            req.setOutOrderId(orderResult.getOutOrderId());
            req.setNotifyUrl(webDomain + "/wechat/applet/notifyUrl");
            req.setReturnUrl(returnUrl);
            req.setUserIp(IpUtils.getIp(request));
            req.setPayMethod(EnumPayMethod.WECHAT_APPLET_MP.getCode());
            req.setQyWebDomain(webDomain);
            req.setOrderTypeEnum(OrderTypeEnum.INQUIRELOGISTICS);
            req.setOpenId(openId);
            PayParam orderAndPay = commonPayService.createOrderAndPay(req);
            if (orderAndPay.getAmount() > 0) {
                if (EnumPayMethod.WECHAT_APPLET_MP.getCode().equals(req.getPayMethod())) {
                    PayOrderResult payOrder = new PayOrderResult();
                    payOrder.setMoney(req.getAmount());
                    payOrder.setReturnUrl(req.getReturnUrl());
                    payOrder.setTitle(req.getSubject());
                    payOrder.setAppletType(appletType);
                    Map<String, String> weixinOrderInfo = WeixinAppletsUtil.wechatAppletsPay(payOrder, req.getUserIp(), req.getOpenId(),
                            webDomain + "/wechat/applet/notifyUrl",
                            req.getOrderTypeEnum().getCode() + "-" + orderAndPay.getOrderId());
                    orderAndPay.setWeixinOrderInfo(weixinOrderInfo);
                } else {
                    throw new BusinessException(ExceptionEnum.ERROR_1825.getCode(), ExceptionEnum.ERROR_1825.getMessage());
                }
            }
            result.setData(orderAndPay);
        } catch (BusinessException e) {
            return Result.failed(e.getCode(), e.getMessage());
        }
        return result;
    }

    @OperLog(operModul = "商户-价格趋势图", operDesc = "价格趋势图")
    @RequestMapping(value = "/merchant/inquire/sku/priceTrend/list")
    public Result<Page<InquireSkuPriceTrendResult>> skuPriceTrendList(@RequestBody JSONObject jsonObject, HttpServletResponse response) {
        Integer pageSize = jsonObject.getInteger("pageSize");
        Integer pageIndex = jsonObject.getInteger("pageIndex");
        PagerInfo pagerInfo = setDefaultPageInfo(pageSize, pageIndex);
        Page<InquireSkuPriceTrendResult> pager = inquireSkuPriceTrendService.getPager(new InquireSkuPriceTrendQuery(), pagerInfo);
        return Result.success(pager);
    }

    @OperLog(operModul = "商户-价格趋势图", operDesc = "价格趋势图")
    @RequestMapping(value = "/merchant/inquire/priceTrend/map")
    public Result<Map<String, List<InquireSkuPriceTrendResult>>> skuPriceTrendMap(@RequestBody JSONObject jsonObject, HttpServletResponse response) {
        Date startTime = jsonObject.getDate("startTime");
        Date endTime = jsonObject.getDate("endTime");
        Map<String, List<InquireSkuPriceTrendResult>> map = inquireSkuPriceTrendService.getMap(null, startTime, endTime);
        return Result.success(map);
    }

    @OperLog(operModul = "商户-期货订单列表", operDesc = "期货订单列表")
    @LoginCheck
    @RequestMapping(value = "/merchant/inquire/order/list")
    public Result<Page<OrderListResult>> orderList(@RequestBody JSONObject jsonObject, HttpServletResponse response) {
        Integer pageSize = jsonObject.getInteger("pageSize");
        Integer pageIndex = jsonObject.getInteger("pageIndex");
        String status = jsonObject.getString("status");
        PagerInfo pagerInfo = setDefaultPageInfo(pageSize, pageIndex);
        Page<OrderListResult> page = inquireOrderService.getPage(getMerchant().getUserId(), status, pagerInfo);
        return Result.success(page);
    }

    @OperLog(operModul = "商户-期货订单详情", operDesc = "期货订单详情")
    @LoginCheck
    @RequestMapping(value = "/merchant/inquire/order/detail")
    public Result<InquireOrderResult> orderDetail(@RequestBody JSONObject jsonObject, HttpServletResponse response) {
        Integer subOrderId = jsonObject.getInteger("subOrderId");
        try {
            InquireOrderResult inquireOrderResult = inquireOrderService.getInquireOrderResult(subOrderId);
            return Result.success(inquireOrderResult);
        } catch (BusinessException e) {
            return Result.failed(e.getCode(), e.getMessage());
        }
    }


    @OperLog(operModul = "商户-检测订单列表", operDesc = "检测订单列表")
    @LoginCheck
    @RequestMapping(value = "/merchant/inquire/testing/order/list")
    public Result<Page<InquireOrderTestingResult>> testingOrderList(@RequestBody JSONObject jsonObject, HttpServletResponse response) {
        Integer pageSize = jsonObject.getInteger("pageSize");
        Integer pageIndex = jsonObject.getInteger("pageIndex");
        String status = jsonObject.getString("status");
        PagerInfo pagerInfo = setDefaultPageInfo(pageSize, pageIndex);
        InquireOrderTestingReq req = new InquireOrderTestingReq();
        req.setMerchantId(getMerchant().getUserId());
        req.setStatus(status);
        Page<InquireOrderTestingResult> pagerByReq = inquireOrderTestingService.getPagerByReq(req, pagerInfo);
        return Result.success(pagerByReq);
    }


    @OperLog(operModul = "商户-检测订单详情", operDesc = "检测订单详情")
    @LoginCheck
    @RequestMapping(value = "/merchant/inquire/testing/order/detail")
    public Result<InquireOrderTestingResult> testingOrderDetail(@RequestBody JSONObject jsonObject, HttpServletResponse response) {
        Integer id = jsonObject.getInteger("id");
        InquireOrderTestingResult detailByIdAndMerchantId = inquireOrderTestingService.getDetailByIdAndMerchantId(id, getMerchant().getUserId());
        return Result.success(detailByIdAndMerchantId);
    }

    @OperLog(operModul = "商户-检测机构列表", operDesc = "检测机构列表")
    @LoginCheck
    @RequestMapping(value = "/merchant/inquire/testing/list")
    public Result<List<InquireSkuTestingMessageResult>> testingList(@RequestBody JSONObject jsonObject, HttpServletResponse response) {
        Integer inquireOrderId = jsonObject.getInteger("inquireOrderId");
        List<InquireSkuTestingMessageResult> inquireSkuTestingMessageResult = null;
        try {
            inquireSkuTestingMessageResult = inquireOrderTestingService.getInquireSkuTestingMessageResult(inquireOrderId);
        } catch (BusinessException e) {
            return Result.failed(e.getCode(), e.getMessage());
        }
        return Result.success(inquireSkuTestingMessageResult);
    }

    @OperLog(operModul = "商户-检测订单支付", operDesc = "检测订单支付")
    @LoginCheck
    @RequestMapping(value = "/merchant/pay/testing", method = {RequestMethod.POST})
    public Result<PayParam> testingOrderPay(HttpServletRequest request, @RequestBody CreateTestingOrderReq req) {
        LoginUser merchant = getMerchant();
        Result<PayParam> result = Result.success(null);
        try {
            req.setUserId(merchant.getUserId());
            req.setType(RoleTypeEnum.MERCHANT.getCode());
            OrderResult testingOrder = inquireOrderTestingService.createTestingOrder(req);
            PayReq payReq = new PayReq();
            payReq.setUserId(merchant.getUserId());
            payReq.setAmount(testingOrder.getPayPrice());
            payReq.setSubject("检测订单支付");
            payReq.setOutOrderId(testingOrder.getOutOrderId());
            payReq.setNotifyUrl(webDomain + "/wechat/applet/notifyUrl");
            payReq.setReturnUrl(req.getReturnUrl());
            payReq.setUserIp(IpUtils.getIp(request));
            payReq.setPayMethod(EnumPayMethod.WECHAT_APPLET_MP.getCode());
            payReq.setQyWebDomain(webDomain);
            payReq.setOrderTypeEnum(OrderTypeEnum.TESTING);
            payReq.setOpenId(req.getOpenId());
            PayParam orderAndPay = commonPayService.createOrderAndPay(payReq);
            if (orderAndPay.getAmount() > 0) {
                if (EnumPayMethod.WECHAT_APPLET_MP.getCode().equals(payReq.getPayMethod())) {
                    PayOrderResult payOrder = new PayOrderResult();
                    payOrder.setMoney(payReq.getAmount());
                    payOrder.setReturnUrl(payReq.getReturnUrl());
                    payOrder.setTitle(payReq.getSubject());
                    payOrder.setAppletType(req.getAppletType());
                    Map<String, String> weixinOrderInfo = WeixinAppletsUtil.wechatAppletsPay(payOrder, payReq.getUserIp(), req.getOpenId(),
                            webDomain + "/wechat/applet/notifyUrl",
                            payReq.getOrderTypeEnum().getCode() + "-" + orderAndPay.getOrderId());
                    orderAndPay.setWeixinOrderInfo(weixinOrderInfo);
                } else {
                    throw new BusinessException(ExceptionEnum.ERROR_1825.getCode(), ExceptionEnum.ERROR_1825.getMessage());
                }
            }
            result.setData(orderAndPay);
            return result;
        } catch (BusinessException e) {
            return Result.failed(e.getCode(), e.getMessage());
        }
    }

    @OperLog(operModul = "商户-取消检测订单", operDesc = "取消检测订单")
    @LoginCheck
    @RequestMapping(value = "/merchant/inquire/test/order/cancel", method = {RequestMethod.POST})
    public Result<MerchantResult> inquireTestOrderCancel(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws BusinessException {
        LoginUser merchant = getMerchant();
        Integer id = jsonObject.getInteger("id");
        Result<MerchantResult> result = Result.success(null);
        inquireOrderTestingService.cancelOrder(id, merchant.getUserId());
        return result;
    }

    @OperLog(operModul = "商户-开票", operDesc = "开票")
    @LoginCheck
    @RequestMapping(value = "/merchant/inquire/order/invoicing", method = {RequestMethod.POST})
    public Result<String> inquireOrderCancelInvoicing(@RequestBody InvoicingOrderReq req, HttpServletRequest request) {
        LoginUser merchant = getMerchant();
        Result<String> result = Result.success(null);
        try {
            req.setMerchantId(merchant.getUserId());
            inquireOrderService.invoicingOrderByInvoicingOrderReq(req);
        } catch (BusinessException e) {
            return Result.failed(e.getCode(), e.getMessage());
        }
        return result;
    }

}
